package cn.liyicun.test.controller;

import cn.hutool.captcha.CaptchaUtil;
import cn.hutool.captcha.ShearCaptcha;
import cn.hutool.captcha.generator.RandomGenerator;
import cn.hutool.core.lang.Validator;
import cn.hutool.extra.servlet.ServletUtil;
import cn.liyicun.test.base.Common;
import cn.liyicun.test.bean.UserInfo;
import cn.liyicun.test.dto.MyResultInfo;
import cn.liyicun.test.exception.MyException;
import cn.liyicun.test.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

@Controller
@Slf4j
public class LoginAndRegController extends BaseController {


    @Autowired
    UserService user;

    @GetMapping("/login")
    public String login1(HttpServletRequest req, HttpServletResponse res) throws IOException {

        HttpSession session = req.getSession(false);
        if (session != null) {
            if (session.getAttribute(Common.USER_SESSION_NAME) != null) {
                res.sendRedirect("main");
                return null;
            }
        }

        return "login";
    }

    @GetMapping("/logout")
    public void logout(HttpServletRequest req, HttpServletResponse res) throws IOException {
        HttpSession session = req.getSession(false);
        if (session != null) {
            session.invalidate();
        }
        res.sendRedirect("/");
    }

    @PostMapping("/login")
    @ResponseBody
    public MyResultInfo login2(HttpServletRequest req, HttpServletResponse res, @RequestParam(name = "username", required = true) String username, @RequestParam("passwd") String passwd, @RequestParam("captcha") String captcha) throws MyException {

        String error = "用户名或密码错误!";


        if (!_captcha(req, captcha)) {
            return MyResultInfo.error("验证码错误!");
        }


        UserInfo userinfo = user.queryByUserName(username);
        if (userinfo == null) {
            return MyResultInfo.error(error);
        }
        if (!userinfo.getPasswd().equals(passwd)) {
            return MyResultInfo.error(error);
        }
        String ip = ServletUtil.getClientIP(req);
        log.info(ip);
Long uid=userinfo.getId();
        HttpSession session = req.getSession();

        session.setAttribute(Common.USER_SESSION_NAME,uid );
        user.updateLoginLog(uid,ip);
        log.info("userinfo:{},ip:{},登陆成功!", userinfo,ip);
        return MyResultInfo.ok("登陆成功!");
    }


    @GetMapping("/register")
    public String register() {
        return "register";
    }

    @PostMapping("/register")
    @ResponseBody
    public MyResultInfo register2(HttpServletRequest req, HttpServletResponse res,@RequestParam("username") String username, @RequestParam("captcha") String captcha, @RequestParam("passwd") String passwd, @RequestParam("passwd2") String passwd2, @RequestParam("fullName") String fullName) throws MyException {
        if (passwd == null || !passwd.equals(passwd2)) {
            return MyResultInfo.error("2次设置的密码不一致!");
        }

        if (passwd.equals(username)) {
            return MyResultInfo.error("用户名不能和密码一样!");
        }
        if (passwd == null || passwd.trim().length()<5) {
            return MyResultInfo.error("密码必须大于等于5位");
        }
        if (fullName == null || fullName.trim().length() <= 0) {
            return MyResultInfo.error("昵称必须设置!");
        }
        if (!Validator.isGeneralWithChinese(fullName)) {
            return MyResultInfo.error("昵称必须是中文字、英文字母、数字和下划线");
        }

        if (!Validator.isGeneral(username)) {
            return MyResultInfo.error("登陆账号必须是英文字母 、数字和下划线");
        }
        if (username == null || username.trim().length()<5) {
            return MyResultInfo.error("登陆账号必须大于等于5位");
        }

        if (!_captcha(req, captcha)) {
            return MyResultInfo.error("验证码错误!");
        }

        if (user.existUserName(username) > 0) {
            return MyResultInfo.error("错误,用户名重复!" + username);
        }

        String ip = ServletUtil.getClientIP(req);
        user.addUser(username, passwd, fullName,ip);

        return MyResultInfo.ok("注册成功,请登录!" + fullName);
    }


    @GetMapping("/captcha")
    public void captcha(HttpServletRequest req, HttpServletResponse response) throws IOException {
//定义图形验证码的长、宽、验证码字符数、干扰线宽度
        ShearCaptcha captcha = CaptchaUtil.createShearCaptcha(100, 40, 4, 4);
        captcha.setGenerator(new RandomGenerator("1234567890", 4));
        captcha.createCode();
//ShearCaptcha captcha = new ShearCaptcha(200, 100, 4, 4);
//图形验证码写出，可以写出到文件，也可以写出到流
        captcha.write(response.getOutputStream());
        String code = captcha.getCode();

        String ip = ServletUtil.getClientIP(req);


        HttpSession session = req.getSession();

        session.setAttribute(Common.CAPTCHA_NAME, code);
//        log.info("session:{},ip:{},code:{},getAttribute:{}",session.getId(),ip ,code, session.getAttribute(Common.CAPTCHA_NAME));
    }

}